using System;
using System.Collections.Generic;
using System.Text;

using Weazel.Microblaze.Simulator.Engine;

namespace Weazel.Microblaze.Simulator.Components.Microblaze.Instructions
{
    public class Lw : MemoryAccessInstruction
    {
        public override int CycleCount
        {
            get { return 1; }
        }

        public Lw()
            : base("lw")
        {
        }

        /// <summary>
        /// Loads a word (32 bits) from the word aligned memory location 
        /// that results from adding the contents of registers rA and rB. 
        /// The data is placed in register rD.
        /// </summary>    
        public override void Execute(MicroblazeComponent MicroblazeComponent)
        {
            uint sa = MicroblazeComponent.ReadRegister(SourceRegisterA);
            uint sb = MicroblazeComponent.ReadRegister(SourceRegisterB);

            //uint memory;

            ReadWordTransaction transaction = new ReadWordTransaction(MicroblazeComponent, sa + sb);
            MicroblazeComponent.BeginDataTransaction(transaction);

            // stall if needed
            while (transaction.Status != Transaction.TransactionStatus.Complete)
                MicroblazeComponent.WaitOneCycle();

            /*
            MemoryAccessStatus status = MicroblazeComponent.DataMemorySpace.ReadWord(sa + sb, out memory);

            if (status == MemoryAccessStatus.Ok)
            {
             **/
                // store to register
             
            MicroblazeComponent.WriteRegister(DestinationRegister, transaction.Value, Address);                          
        }


        public override string ToString()
        {
            return string.Format("lw r{0}, r{1}, r{2}",
              DestinationRegister,
              SourceRegisterA,
              SourceRegisterB
            );
        }
    }
}
